<template>
  <div class="procure-outbound-add">
    <div class="info">
      <div>
        <div class="left">
          <p class="creater mr40">制单人：{{ userInfo.createBy || "-" }}</p>
          <p class="mr40">制单时间：{{ userInfo.createTime || "-" }}</p>
          <p>调拨编码：{{ userInfo.deliveryNo || "-" }}</p>
        </div>
        <div class="right">
          <el-button type="info" plain @click="$router.push({ path: '/procure/inventory-allot', query: {} })">返回</el-button>
        </div>
      </div>
    </div>

    <el-container class="content">
      <el-aside>
        <header>
          <div class="supper">
            <div>
              <p>出库仓</p>
              <el-select
                v-model="houseValue"
                placeholder="请选择"
                clearable
                @change="
                  val => {
                    changeHouse(val);
                  }
                "
              >
                <el-option
                  v-for="item in houseList"
                  :disabled="item.warehouseId === rkHouse"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </div>
            <el-button class="ml20" :disabled="!houseValue" type="primary" @click="toPath"> 添加商品 </el-button>
          </div>
          <div class="count">
            <h3>合计</h3>
            <div>
              <p>实际调拨数量：{{ count.sjNum1 }}</p>
              <p class="ml100">实际调拨件数：{{ count.sjNum2 }}</p>
            </div>
          </div>
        </header>

        <!-- 商品列表 -->
        <div class="products-list" style="overflow-x: auto">
          <div class="my-table" style="width: 1500px">
            <div class="table-header">
              <div>
                <div>
                  <div class="col1">商品信息</div>
                  <div class="col2">商品类目</div>
                  <div class="col3">关联客户</div>
                  <div class="col4">单位</div>
                  <div class="col5">实际调拨数量</div>
                  <div class="col6">实际调拨件数</div>
                  <div class="col55">可调拨数量</div>
                  <div class="col66">可调拨件数</div>
                  <div class="col7">仓库</div>
                  <div class="col8">操作</div>
                </div>
              </div>
            </div>

            <div class="table-body" v-if="list.length > 0">
              <div class="list-item mb15" v-for="(item, index) in list" :key="index">
                <p>
                  关联客户：
                  {{
                    item.customerName && item.customerName !== "null" ? item.customerName + "-" + item.customerMobileCode : "-"
                  }}
                </p>
                <template v-for="(item2, index2) in item.inventoryAllotDetails" :key="index2">
                  <div>
                    <div class="row">
                      <div class="col1">
                        <div>
                          <div class="left">
                            <img :src="item2.mainPicUrl" alt="" />
                          </div>
                          <div class="right">
                            <h3 class="name text-break">{{ item2.productAliasName || "-" }}</h3>
                            <p style="white-space: break-spaces; word-break: break-all">
                              <!-- {{ getSpes(item2.properties) }} -->
                              {{ item2.skuSpecification }}
                            </p>
                            <p>SKU编码：{{ item2.skuCode || "-" }}</p>
                            <p>ID：{{ item2.productId || "-" }}</p>
                          </div>
                        </div>
                      </div>
                      <div class="col2">
                        {{ item2.categoryPreview || "-" }}
                      </div>
                      <div class="col3" style="white-space: break-spaces; word-break: break-all">
                        {{ item2.customerName ? item2.customerName + "-" + item2.customerMobileCode : "-" }}
                      </div>
                      <div class="col4">
                        {{ getName(item2.productUnit) || "-" }}
                      </div>
                      <div class="col5">
                        <el-input-number
                          :min="1"
                          :max="item2.availuableNum || 1"
                          :precision="0"
                          controls-position="right"
                          style="width: 100px"
                          v-model="item2.allotQuantity"
                          @change="
                            () => {
                              item2.allotPartQuantity = item2.allotQuantity ? item2.partNum * Number(item2.allotQuantity) : 0;
                            }
                          "
                          @keydown="channelInputLimit"
                        ></el-input-number>
                      </div>
                      <div class="col6">
                        <el-input-number
                          :min="1"
                          :max="item2.availuablePartNum || 1"
                          :precision="0"
                          controls-position="right"
                          style="width: 100px"
                          v-model="item2.allotPartQuantity"
                          @keydown="channelInputLimit"
                        ></el-input-number>
                        <!-- {{ item2.allotQuantity ? item2.partNum * Number(item2.allotQuantity) : 0 }} -->
                      </div>
                      <div class="col55">
                        <span>{{ item2.availuableNum }}</span>
                      </div>
                      <div class="col66">
                        <span>{{ item2.availuablePartNum }}</span>
                      </div>
                      <div class="col7">
                        <span>{{ item2.warehouseName || "-" }}</span>
                      </div>
                      <div class="col8">
                        <el-button @click="clickDel(item2)" size="small" link type="primary">移除</el-button>
                      </div>
                    </div>
                    <div class="tips">
                      <p class="label">备注</p>
                      <!-- <el-input maxlength="200" v-model="item2.remark" placeholder="请输入"></el-input> -->
                      <RemarkEditor v-model="item2.remark" />
                    </div>
                    <div v-if="item.inventoryAllotDetails[index2 + 1]" class="block-empty"></div>
                  </div>
                </template>
              </div>
            </div>
            <div v-else style="display: flex; justify-content: center; width: 100%">
              <el-empty description="暂无数据" />
            </div>
          </div>
        </div>
      </el-aside>
      <el-main width="300px">
        <div class="rkHouse mb20">
          <p class="mb10">入库仓</p>
          <el-select v-model="rkHouse" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in houseList"
              :disabled="item.warehouseId === houseValue"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </div>
        <div class="ck-time mb20">
          <p>期望出库日期</p>
          <el-date-picker
            v-model="ckTime"
            type="datetime"
            value-format="YYYY-MM-DD hh:mm:ss"
            placeholder="请选择"
            style="width: 100%"
          />
        </div>
        <div class="price mb20">
          <p class="mb10">调拨费用</p>
          <el-input-number
            :min="0"
            controls-position="right"
            style="width: 100%"
            v-model="allotPrice"
            placeholder="请输入"
            @keydown="channelInputLimit"
          ></el-input-number>
        </div>
        <div class="divider"></div>

        <!-- 关联借调客户信息 -->
        <SecondCustomer ref="secondCustomerRef" />
        <div class="divider"></div>

        <!-- 订单备注 -->
        <div class="ck-tips">
          <p class="label">订单备注</p>
          <!-- <el-input maxlength="200" v-model="textarea" :rows="10" type="textarea" placeholder="请输入" /> -->
          <RemarkEditor v-model="textarea" />
        </div>
      </el-main>
    </el-container>

    <!-- 操作按钮栏 -->
    <div class="action-wrap">
      <!-- <el-button type="info" plain>取消</el-button> -->
      <el-button type="primary" :disabled="list.length <= 0" @click="submit">提交调拨</el-button>
    </div>

    <!-- 确认暂存的list会清空 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenClear"
      :message="'您正在重新选择出库仓，当前商品信息将被重置，重新添加商品，请问是否继续当前操作？'"
      :submitBtnText="'继续'"
      @submit="returnSubmitClear"
      @cancel="returnCancelClear"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { getSuppliers } from "@/apis/products/specifications";
import moment from "moment";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { getTempProductSkuList, newInboundOrder, delTempProductSku } from "@/apis/procure/entry";
import { ListPage } from "@/apis/procure/warehouse";
import { ElMessage, ElMessageBox } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import china from "@/utils/china.json";
import { createOtherDeliveryOrderInfo } from "@/apis/procure/outbound";
import { getSelectedProducts, removeAllotProduct, create } from "@/apis/procure/inventory-allot";
import { _throttle, channelInputLimit } from "@/utils";
import RemarkEditor from "@/components/RemarkEditor";
import SecondCustomer from "@/views/procure/outbound/components/secondCustomer.vue";

const secondCustomerRef = ref();
const houseList = ref([]); //出库仓下拉数据
const houseValue = ref(""); //选中的出库仓
const rkHouse = ref(""); //选中的入库仓
const allotPrice = ref(null); //调拨费用
const detail = ref({});
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const storeList = ref([]); //收货仓库下拉数据
const ckTime = ref("");
const textarea = ref("");
const userInfo = ref({});
const _isOpenClear = ref(false);
const psList = ref([{ label: "配送人A", value: 1 }]); //配送人员下拉数据
const psValue = ref(null); //选中的配送人员
const form = ref({}); //收货信息表单数据
const formRef = ref();
const form2 = ref({}); //新建配送人表单数据
const form2Ref = ref();
const mapList = ref(china);
const dialogVisible = ref(false);
const count = ref({ sjNum1: 0, sjNum2: 0 });

watch(
  () => list.value,
  val => {
    count.value = { sjNum1: 0, sjNum2: 0 };
    let LIST = [];
    for (let item of val) {
      for (let obj of item.inventoryAllotDetails) {
        LIST.push(obj);
      }
    }
    LIST?.map(item => {
      count.value.sjNum1 += item.allotQuantity ? Number(item.allotQuantity) : 0;
      count.value.sjNum2 += item.allotPartQuantity ? Number(item.allotPartQuantity) : 0;
    });
  },
  { deep: true }
);

onMounted(async () => {
  const info = await createOtherDeliveryOrderInfo({ type: 3 });
  userInfo.value = info.data;

  const res2 = await ListPage({ page: 1, size: 9999 }); //入库仓
  storeList.value = res2.data.records;
  houseList.value = res2.data.records;

  if (route.query.warehouseId) houseValue.value = route.query.warehouseId;

  getList();
});

const changeHouse = val => {
  if (route.query.warehouseId && route.query._time && list.value.length > 0) {
    _isOpenClear.value = true;
  } else {
    returnSubmitClear();
  }
};

const toPath = () => {
  if (route.query._time && houseValue.value === route.query.warehouseId) {
    router.push({
      path: "/procure/inventory-allot/select-prod",
      query: { warehouseId: houseValue.value, _time: route.query._time }
    });
  } else {
    router.push({
      path: "/procure/inventory-allot/select-prod",
      query: { warehouseId: houseValue.value, _time: new Date().getTime() }
    });
  }
};
const returnSubmitClear = () => {
  _isOpenClear.value = false;
  router.push({
    path: "/procure/inventory-allot/add",
    query: { warehouseId: houseValue.value, _time: new Date().getTime() }
  });
  setTimeout(() => {
    list.value = [];
  }, 300);
};
const returnCancelClear = () => {
  houseValue.value = route.query.warehouseId;
};

//打开新建配送人弹窗
const openAdd = () => {
  dialogVisible.value = true;
};
//关闭新建配送人弹窗
const closeAdd = () => {
  form2Ref.value.resetFields();
  dialogVisible.value = false;
};

//确认新建配送人
const addSubmit = () => {
  form2Ref.value.validate((valid, fields) => {
    if (valid) {
      closeAdd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const cascaderRef = ref();
const handleChange = value => {
  console.log("producerList", value);
  const nodes = cascaderRef.value.getCheckedNodes();
  console.log("找到了当前选中的节点数据===", nodes);
  // form.value.provinceId = nodes[0].pathValues[0];
  // form.value.cityId = nodes[0].pathValues[1];
  // form.value.districtId = nodes[0].pathValues[2];
  // form.value.provinceName = nodes[0].pathLabels[0];
  // form.value.cityName = nodes[0].pathLabels[1];
  // form.value.districtName = nodes[0].pathLabels[2];
};

const clickDel = row => {
  removeAllotProduct({
    allotKey: route.query._time,
    warehouseProductsId: row.warehouseProductsId
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "移除成功！",
        type: "success"
      });
      getList();
    }
  });
  // console.log("删除暂存数据", row);
};

const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

//确认创建出库单
const submit = _throttle(() => {
  if (!(houseValue.value && rkHouse.value)) {
    return ElMessage({
      message: "请选择出库仓和入库仓！",
      type: "error"
    });
  }

  let LIST = [];
  for (let item of list.value) {
    for (let obj of item.inventoryAllotDetails) {
      LIST.push(obj);
    }
  }
  let flag = LIST.some(item => {
    if (Number(item.allotQuantity) <= 0 || !item.allotQuantity) {
      ElMessage({
        message: "请填写完整商品的“实际调拨数量”",
        type: "error"
      });
      return true;
    }
  });

  if (!flag) {
    const jdInfo = secondCustomerRef.value.getData();
    create({
      allotKey: route.query._time,
      allotNo: userInfo.value.deliveryNo,
      calloutWarehouseId: houseValue.value, //出库id
      intoWarehouseId: rkHouse.value, //入库id
      expectStockTime: ckTime.value,
      allotAmount: allotPrice.value,
      remark: textarea.value,
      productInfos: LIST,
      secondmentCustomerId: jdInfo?.customerId || "", //借调客户id
      secondmentCustomerName: jdInfo?.receivingName || "", //借调客户名称
      secondmentCustomerPhone: jdInfo?.receivingMobile || "", //借调客户号码
      secondmentCustomerAddress: jdInfo?.address || "", //借调客户地址
      secondmentCustomerRemark: jdInfo?.secondmentCustomerRemark || "" //借调客户备注
    }).then(res => {
      if (res.code === 200) {
        ElMessageBox.confirm("", "", {
          cancelButtonText: "取消",
          confirmButtonText: "前往查看",
          dangerouslyUseHTMLString: true,
          message: "<div class='img'></div><p>调拨单创建成功，可前往调拨单列表中查看！</p>",
          customClass: "my-success-messagebox",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false
        })
          .then(() => {
            console.log("前往出库列表查看");
            router.push({ path: "/procure/inventory-allot" });
          })
          .catch(async () => {
            // 取消

            const info = await createOtherDeliveryOrderInfo({ type: 3 });
            userInfo.value = info.data;

            getList();
          });
      }
    });
  }
}, 1000);

//查询列表数据
const getList = () => {
  if (route.query._time) {
    getSelectedProducts({
      allotKey: route.query._time
    }).then(res => {
      if (res.code === 200) {
        // detail.value = res.data;
        list.value = res.data;
      }
    });
  }
};
//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.divider {
  border-bottom: 1px solid #e2e8f0;
  margin: 20px -20px;
}
.block {
  height: 10px;
  background-color: white;
  border-top: none !important;
  border-bottom: none !important;
  border-left: 1px solid #e1e6ed !important;
}
.block-empty {
  height: 10px;
  background-color: white;
  border-left: 1px solid #e1e6ed !important;
  border-right: 1px solid #e1e6ed !important;
}

.procure-outbound-add {
  height: calc(100% - 64px);
  overflow-y: auto;
  padding: 0 20px 64px 20px;
  position: relative;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .info {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    & > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 0;
      border-bottom: 1px solid #e2e8f0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      .creater {
        color: #1a1a1a;
        font-weight: bold;
      }
    }
  }
  .content {
    height: calc(100% - 75px);
    :deep(.el-aside) {
      flex: 1;
      padding: 20px 20px 20px 0;
      header {
        margin-bottom: 18px;
        .supper {
          display: flex;
          justify-content: space-between;
          & > div {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex: 1;
          }
          p {
            width: 52px;
          }
          .el-select {
            flex: 1;
          }
        }
        .count {
          display: flex;
          justify-content: space-between;
          padding: 10px 20px;
          background-color: #f6f8fa;
          margin-top: 20px;
          h3 {
            font-size: 16px;
            font-weight: normal;
          }
          & > div {
            display: flex;
          }
        }
      }
      .products-list {
        .table-header {
          background-color: #f2f6fc;
          margin-bottom: 10px;
        }
        .table-body {
          .list-item {
            // margin-bottom: 10px;
            & > p {
              line-height: 40px;
              background-color: #f5f7fa;
              padding-left: 18px;
              color: #3d3d3d;
              font-size: 14px;
              border: 1px solid #e1e6ed;
              border-bottom: none;
            }
            & > div {
              display: block !important;
            }
            & > div > div.row {
              border: 1px solid #e1e6ed;
              display: flex;
              // align-items: center;
              // padding: 14px 20px;
              &:not(:first-of-type) {
                border-left: none;
              }
              &:not(:last-of-type) {
                & > div:not(:last-of-type) {
                  border-right: 1px solid #e1e6ed;
                }
              }
              & > div {
                padding: 14px 20px;
                display: flex;
                align-items: center;
              }
            }
            .col1 {
              & > div {
                display: flex;
              }

              .left {
                img {
                  width: 80px;
                  height: 80px;
                  border-radius: 4px;
                }
              }
              .right {
                padding-left: 18px;
                .name {
                  font-size: 14px;
                  color: #3d3d3d;
                  margin-bottom: 5px;
                }
                p {
                  font-size: 12px;
                  color: #86909c;
                  margin-bottom: 5px;
                }
              }
            }
            .tips {
              display: flex;
              align-items: center;
              padding: 16px 14px;
              border-top: none;
              border-left: 1px solid #e1e6ed !important;
              border-right: 1px solid #e1e6ed !important;
              border-bottom: 1px solid #e1e6ed !important;
              p.label {
                width: 38px;
              }
              .el-input {
                flex: 1;
                .el-input__wrapper {
                  background-color: #f2f3f5;
                }
              }
            }
          }
        }
        .table-header {
          & > div {
            & > div {
              & > div {
                padding: 14px 20px;
              }
            }
          }
        }
        .table-header,
        .table-body {
          .col1 {
            // width: 45%;
            flex: 1;
            min-width: 300px;
          }

          .col4,
          .col7,
          .col8 {
            width: 80px;
            box-sizing: border-box;
          }
          .col2,
          .col3 {
            width: 120px;
            box-sizing: border-box;
          }
          .col5,
          .col6 {
            width: 125px;
            box-sizing: border-box;
          }
          .col55,
          .col66 {
            width: 120px;
            box-sizing: border-box;
          }
          & > div > div:first-of-type {
            display: flex;
            justify-content: space-between;
          }
        }
      }
    }
    :deep(.el-main) {
      width: 300px;
      flex: none;
      background-color: #f6f8fa;
      border-left: 1px solid #e2e8f0;
      .price {
        .el-input__inner {
          text-align: left;
        }
      }
      .ck-time,
      .ps-people {
        p {
          width: 120px;
          margin-bottom: 10px;
        }
        .el-select {
          flex: 1;
        }
      }
      .ps-people {
        & > div {
          display: flex;
          .el-button {
            font-size: 12px;
          }
        }
      }
      .kh-info {
        h3 {
          color: #86909c;
          font-weight: normal;
          margin: 20px 0 16px 0;
        }
        p {
          color: #86909c;
          margin-bottom: 10px;
        }
        b {
          font-weight: normal;
          color: #1a1a1a;
        }
      }
      .sh-info {
        & > p {
          font-size: 16px;
          color: #86909c;
          margin-bottom: 10px;
        }
        .el-form-item {
          flex-direction: column;
        }
        .el-form-item__label-wrap {
          margin-left: 0 !important;
        }
      }
      .ck-tips {
        p.label {
          color: #4e5969;
          margin-bottom: 16px;
        }
      }
    }
  }
  .action-wrap {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    height: 64px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  }
}
</style>
